/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package auctions;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Vector;

/**
 *
 * @author zxyang
 */
public class AscendingAuction extends Auction {
    
    public AscendingAuction(int auctNum, String outputFile, int numBidders, Double reserve, int paymentRule){
    	super(auctNum, outputFile, numBidders, reserve, paymentRule);
    }

    public Vector<AuctionResults> getWinner(){
        boolean over = true;
        Vector<AuctionResults> aresults = new Vector<AuctionResults>();
        
        double maxBid=0;
        int maxBidder=0;
        double askPrice = _reserve;
        int ascendNum=1;
        AuctionResults currAuctRes=null;
        double price=0;
        while(true){
            over = true;
            if(ascendNum>1){
                currAuctRes = aresults.get(ascendNum-2);
            }
            for(int i=0; i<_agents.size();i++){
                if(_agents.get(i).getBid(_auctionNumber,askPrice,currAuctRes)>=askPrice){
                    over = false;
                }
            }
            if(over) break;

            maxBid = 0;
            maxBidder = 0;
            Vector<Double> bids = new Vector<Double>();  //This could be extended
            for (int agent = 0; agent<_agents.size(); agent++) {
                bids.add(_agents.get(agent).getBid(_auctionNumber,askPrice,currAuctRes));
                if (bids.get(agent) > maxBid) {
                    maxBid = bids.get(agent);
                    maxBidder = agent;
                }
            }
            
            ArrayList<Double> sortedBids = new ArrayList<Double>(bids);
            Collections.sort(sortedBids);		
            int priceIndex = sortedBids.size() - this._paymentRule;
            if (priceIndex < 0)  { 
                price = this._reserve;
            } else { 
                price = sortedBids.get(priceIndex);
            }
            if (price<askPrice) price=askPrice;
            aresults.add(new AuctionResults(price,bids,maxBidder,_auctionNumber));
			askPrice= sortedBids.get(sortedBids.size()-1)+1;
            ascendNum++;
        }		
        _agents.get(maxBidder).addWinnings(_auctionNumber, price);
        _ars = aresults;
        return aresults;
        
    }

	@Override
	public AuctionType getType() {
		return AuctionType.ASCENDING;
	}


}
